package com.anysoft.login;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.AccountLoginBean;
import com.anysoft.bean.ResultBean;
import com.anysoft.bean.UserBean;
import com.anysoft.event.FundBannerLoginEvent;
import com.anysoft.event.HomeBannerLoginEvent;
import com.anysoft.user.UserManageListviewActivity;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.AnalyticsEventUtils;
import com.anysoft.utils.AnalyticsUtils;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.ParamUtil;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.utils.login.PBKDF2_Utils;
import com.anysoft.view.ViewLoginNinePointPwd;
import com.anysoft.view.dialog.DialogUtils;
import com.anysoft.web.SearchTradeNewActivity;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.anysoft.MentorConst.ACCOUNT_LOCKOUT;
import static com.anysoft.utils.BitmapUtils.getDiskBitmap;

/**
 * Created by wwq on 2017/1/4.
 * 手势登录
 */

public class LoginByGestureActivity extends BaseActivity {

    public static int PWD_WIDTH = 0;
    public static int PWD_HEIGHT = 0;
    protected ViewLoginNinePointPwd nv;// 九宫格View
    @BindView(R.id.tv_login_pwd_forget)
    TextView tvLoginPwdForget;
    @BindView(R.id.tv_login_pwd_others)
    TextView tvLoginPwdOthers;
    @BindView(R.id.ll_login_pwd_bottom)
    LinearLayout ll_login_pwd_bottom;
    @BindView(R.id.civ_user_icon)
    CircleImageView civUserIcon;
    @BindView(R.id.tv_gesture_login_username)
    TextView tvGestureLoginUsername;
    @BindView(R.id.tv_gesture_login_tip)
    TextView tvGestureLoginTip;
    @BindView(R.id.ll_login_pwd_top)
    LinearLayout ll_login_pwd_top;
    @BindView(R.id.ll_login_pwd_view)
    LinearLayout ll_login_pwd_view;


    private String userId = "";
    private int faileTimes = MentorConst.GESTURE_OR_FINGERPRINT_FAIL_TIMES;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login_gesture);
        ButterKnife.bind(this);

        userId = getIntent().getStringExtra("userId");

        UserBean userBean = findUser(userId);
        if (userBean != null) {
            String userName = userBean.getUserName();
            tvGestureLoginUsername.setText(ParamUtil.formatUserName(userName));

            String pathUrl = userBean.getUserImgPath();
            if (!TextUtils.isEmpty(pathUrl)) {
                Logger.t("pathUrl").d(pathUrl);
                Bitmap bitmap = getDiskBitmap(pathUrl);
                if (bitmap != null) {
                    civUserIcon.setImageBitmap(bitmap);
                }
            } else {
                if ("0".equals(userBean.getSex())) {//女
                    civUserIcon.setImageResource(R.mipmap.icon_user_w);
                } else if ("1".equals(userBean.getSex())) {//男
                    civUserIcon.setImageResource(R.mipmap.icon_user_m);
                } else {
                    civUserIcon.setBackground(getResources().getDrawable(R.mipmap.icon_user));
                }
//                civUserIcon.setBackground(getResources().getDrawable(R.mipmap.icon_user));
            }
        } else {
            civUserIcon.setBackground(getResources().getDrawable(R.mipmap.icon_user));
        }

        ll_login_pwd_view = (LinearLayout) findViewById(R.id.ll_login_pwd_view);
        ll_login_pwd_bottom = (LinearLayout) findViewById(R.id.ll_login_pwd_bottom);
        ll_login_pwd_top = (LinearLayout) findViewById(R.id.ll_login_pwd_top);

        measure();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    public void measure() {
        WindowManager wm = (WindowManager) getBaseContext().getSystemService(
                Context.WINDOW_SERVICE);

        int height = wm.getDefaultDisplay().getHeight();
        PWD_WIDTH = wm.getDefaultDisplay().getWidth();
        PWD_HEIGHT = height;

        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);

        ll_login_pwd_top.measure(w, h);
        PWD_HEIGHT = PWD_HEIGHT - ll_login_pwd_top.getMeasuredHeight();

        ll_login_pwd_bottom.measure(w, h);
        PWD_HEIGHT = PWD_HEIGHT - ll_login_pwd_bottom.getMeasuredHeight();

        if (PWD_WIDTH != 0 && PWD_HEIGHT != 0) {
            init();
        }
    }

    protected void init() {
        nv = new ViewLoginNinePointPwd(this, PWD_WIDTH, PWD_HEIGHT);
        ll_login_pwd_view.addView(nv);

        nv.SetOnPwdSetSucessListener(new ViewLoginNinePointPwd.OnPwdSetSucessListener() {
            @Override
            public void OnPwdSetSucessListener(String password) {
                login(password);
            }
        });
    }

    private void login(String gesturePwd) {
        showLoading(mActivity);
        Map<String, String> params = new HashMap<>();

        params.put("identityNo", userId);
        params.put("identityType", getUserType(userId));
        params.put("fundCustomerNo", getCustomerNo(userId));
        params.put("loginState", "2");//开启或者修改的内容 	1指纹  2手势
        params.put("fingerprintKey", "");
        String pwd_key = PBKDF2_Utils.getRawKey(getGestureSalt(userId), gesturePwd);
        String local_key = getLocalSecretKey(mActivity, userId);
        String final_key = HttpUtils.getMD5(pwd_key + local_key);
        MentorLogger.Log(TAG + "---final_key:", final_key);
        params.put("signKey", final_key);
        params.put("randomKey", getGestureRandomKey(userId));
        params.put("mobileStyle", Build.MANUFACTURER);
        OkGo.<String>post(HostConstant.VALIDATE_SIGN_FINGER_PRINT_CONFIRM)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateJson(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                        hideLoading();
                        HostConstant.SKIP_TYPE = "";
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void UpdateJson(String json) {
        hideLoading();
        AccountLoginBean bean = null;
        try {
            bean = new Gson().fromJson(json, AccountLoginBean.class);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        ResultBean resultBean = checkStateBean(bean, json);
        if (!resultBean.isSuccess()) {
            if ("-4032".equals(resultBean.getCode()) || "-4058".equals(resultBean.getCode())) {
                DialogUtils utils = new DialogUtils();
                utils.contentAlert(mActivity, "提示", resultBean.getTip(), "确定", "");
                utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                    @Override
                    public void OnContentDialogSbtnClick() {
//                        clearGesture(userId);
//                        startActivity(new Intent().setClass(LoginByGestureActivity.this, LoginActivity.class));
                        clearUserPwd(userId);
                        Intent intent = new Intent().setClass(mActivity, UserIconLoginActivity.class);
                        intent.putExtra("userId", userId);
                        startActivity(intent);
                        finish();
                    }
                });
            } else if (ACCOUNT_LOCKOUT.equals(resultBean.getCode())) {
                DialogUtils utils = new DialogUtils();
                utils.contentAlert(mActivity, "提示", resultBean.getTip(), "确定", "");
                utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                    @Override
                    public void OnContentDialogSbtnClick() {
                        finish();
                    }
                });
            } else {
                tvGestureLoginTip.setText(resultBean.getTip());
                if (faileTimes > 1) {
                    faileTimes--;
                } else {
                    PreferencesUtils.putBoolean(this, userId + "CanGesture", false);
                    //System.out.println("userId--" + userId + ",sp--" + sp.getBoolean(userId + "CanGesture", true));
                    DialogUtils utils = new DialogUtils();
                    utils.contentAlert(mActivity, "提示", "您已连续三次输入手势错误，请使用其他登录方式", "确定", "");
                    utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                        @Override
                        public void OnContentDialogSbtnClick() {
                            Intent intent = new Intent().setClass(mActivity, UserIconLoginActivity.class);
                            intent.putExtra("userId", userId);
                            startActivity(intent);
                            finish();
                        }
                    });
                }
            }
            HostConstant.SKIP_TYPE = "";
            return;
        }

        loginSuccess(bean);
    }

    private void loginSuccess(AccountLoginBean bean) {
        AnalyticsEventUtils.toLoginGesturesEvent(this);
        AnalyticsUtils.onAnalyticsLogin(bean.getData().getIdentityNo());
        showToast("登录成功");
        UserBean userBean = new UserBean();
        userBean.setUserName(bean.getData().getRealName());
        userBean.setUserId(userId);
        userBean.setUserType(getUserType(userId));
        userBean.setToken(bean.getData().getToken());
        userBean.setFundCustomerNo(bean.getData().getFundCustomerNo());
        saveUser(userBean, bean);
        PreferencesUtils.putString(this, MentorConst.LAST_LOGIN_USER_ID, userId);
        if ("from_redeem".equals(HostConstant.SKIP_TYPE)) {
            ActivityUtils.gotoAssetsFundActivity(this);
        } else if ("from_salary".equals(HostConstant.SKIP_TYPE)) {
            ActivityUtils.gotoFixInvestmentAllActivity(this);
        } else if ("from_query".equals(HostConstant.SKIP_TYPE)) {
            startActivity(new Intent().setClass(this, SearchTradeNewActivity.class));
        } else if ("from_home_banner".equals(HostConstant.SKIP_TYPE)) {
            EventBus.getDefault().post(new HomeBannerLoginEvent(true));
        } else if ("from_fund_banner".equals(HostConstant.SKIP_TYPE)) {
            EventBus.getDefault().post(new FundBannerLoginEvent(true));
        }
        HostConstant.SKIP_TYPE = "";
        finish();
    }


    @OnClick({R.id.tv_login_pwd_forget, R.id.tv_login_pwd_others})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login_pwd_forget:
                ActivityUtils.gotoIconLoginActivity(mActivity, true, userId);
                break;
            case R.id.tv_login_pwd_others:
                startActivity(new Intent().setClass(mActivity, UserManageListviewActivity.class));
                finish();
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            HostConstant.SKIP_TYPE = "";
            finish();
        }
        return true;
    }
}
